import React, { useRef,useEffect ,useState,forwardRef,useImperativeHandle} from 'react'
import { withRouter } from 'react-router-dom'
import MyTable from '@/components/common/table'
import Role from '@/api/role'
import Menu from '@/api/menu'

import { Input ,Button,Modal,Form,Spin,Tree} from 'antd'
import { formItemLayout } from '@/config/layout'
import moment from 'moment';
const RoleList = () => {
  const tableRef: RefType = useRef()
  const rowEdit: RefType = useRef()
 
  const columns = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      render:(text,record,index)=>{
        return index+1
      }
    },
    {
      title: '角色名称',
      align: 'center',
      dataIndex: 'rolename',
      key:'rolename',
      
    },
    {
      title: '角色描述',
      align: 'center',
      dataIndex: 'roleexplain',
      key:'roleexplain',
    },
    
    {
      title: '修改时间',
      align: 'center',
      dataIndex: 'modifytime',
      render:(txt)=>{
        return moment(txt).format('YYYY-MM-DD HH:mm')
      }
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'scan',
      width:'1000',
      render:(text,record,index)=>{
        return <div>
          <Button className="btn" onClick={()=>edit(record)} size="small">编辑</Button>
          <Button style={{marginLeft:'10px'}} className="btn" onClick={()=>del(record)} size="small">删除</Button>
         
        </div>
      }
    }
  ]
  // 添加
  const add = () => {
    rowEdit.current.init('');
  }
   // 修改
   const edit = (record:any) => {
    rowEdit.current.init(record.roleid);
  }
  // 删除
  const del = (record:any) => {
    Modal.confirm({
      title: '确认删除角色 - '+record.rolename+'？',
      
      onOk() {
        Role.roleDel({
          roleid:record.roleid,
          isFormData:true
        }).then(()=>{
          tableRef.current.update();
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  return (
    <> 
      <div style={{overflow:'hidden'}}><Button className="fr" onClick={add} style={{marginBottom:'15px'}} type="primary">
      新增角色
      </Button></div>
      <MyTable
        apiFun={Role.getList}
        columns={columns}
        ref={tableRef}
        extraProps={{ results: 10 }}
      />
      <RoleNewCom ref={rowEdit} callback={()=>{
        tableRef.current.update();
      }}/>
    </>
  )
}

//新建/修改角色
const RoleNew = (props,refs) => {
  const [loading, setLoading] = useState<boolean>(false)
  //显示隐藏弹窗
  const [isModalVisible, setIsModalVisible] = useState(false);
   //显示隐藏树
   const [isTreeVisible, setIsTreeVisible] = useState(false);
   //默认选中
   const [defauleChecked,setdDefaultCheck] = useState([]);
  //橘色is
  const [roleId,setId] = useState('');
  //form
  const [form] = Form.useForm()
  const { setFieldsValue } = form
  //菜单树
  const [treeData,setTreeData] = useState<any[]>([]);
  //获取菜单树
  const getTree = ()=>{
    Menu.getTree().then((res)=>{
      let data = handledata(res.data);
      setTreeData(data);
    });
  }

  //  let fieldNames = { title: 'menuname', key: 'menuid', children: 'children' };
  const handledata = (data)=>{
    data.map((e,i)=>{
      data[i]['title'] = e['menuname']
      data[i]['key'] = e['menuid'];
      if(e['children']&&e['children'].length>0){
        e['children'] = handledata(e['children']);
      }
      return 1
    })

    return data;
  }
  useEffect(()=>{
    getTree();
  },[])
  useImperativeHandle(refs, () => ({
    init: (id) => {
      setId(id);
      if(id){
        getDetail(id);
      }else{
        setFieldsValue({
          menuids:[],
          roleexplain:'',
          rolename:''
        });
        showModal();
        setdDefaultCheck([]);
        setIsTreeVisible(true)
      }
     
    }
  }))
  //获取详情
  const getDetail = (id)=>{
    Role.roleDetail({
      'roleid':id
    }).then((res)=>{
      console.log(res);
      let newmenuids = [];
      let menus = res['data']['menus'];
      menus.map((e)=>{
        newmenuids.push(e['menuid']);
        return 1
      })
      setFieldsValue({
        menuids:newmenuids,
        roleexplain:res.data['roleexplain'],
        rolename:res.data['rolename']
      });
      setdDefaultCheck(newmenuids);
      setIsTreeVisible(true)
      showModal();
    })
  }
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };
  //确定
  const handleOk = () => {
    form.validateFields().then((vals) => {
      const Obj = form.getFieldsValue()
      setLoading(true)

      const fn = roleId===''?Role.roleAdd:Role.roleEdit;
      const params = {
        ...Obj,
        ...roleId===''?{}:{'roleid':roleId}
      };
      fn(params).then((res)=>{
        handleCancel();
      })
    }).catch(info => {
      
    })
  };
  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setId('');
    setLoading(false);
    setIsTreeVisible(false);
    props.callback&&props.callback();
  };
  const handleSubmit = () => {
    
    setTimeout(() => {
      setLoading(false)
      
    }, 1000)
  }
  const onSelect = (selectedKeys: React.Key[], info: any) => {
    console.log('selected', selectedKeys, info);
  };

  const onCheck = (checkedKeys, info: any) => {
    console.log('onCheck', checkedKeys, info);
    setFieldsValue({
      menuids:checkedKeys
    });
  };

  return <Modal 
    title="角色设置" 
    visible={isModalVisible} 
    onOk={handleOk} 
    onCancel={handleCancel}
    width={600}
    maskClosable={false}
    >

    <Spin spinning={loading}>
      <Form {...formItemLayout} form={form} onFinish={handleSubmit}>
        <Form.Item
          label="角色名"
          name="rolename"
          rules={[
            {
              required: true,
              message: '请输入角色名'
            }
          ]}
        > 
          <Input placeholder="请输入角色名" />
        </Form.Item>
        <Form.Item
          label="角色备注"
          name="roleexplain"
        >
          <Input.TextArea  placeholder="请输入角色备注" />
        </Form.Item>
        <Form.Item
          label="角色菜单"
          name="menuids"
        >
          {
            isTreeVisible&& <Tree
            checkable
            defaultCheckedKeys={defauleChecked}
            onSelect={onSelect}
            onCheck={onCheck}
            treeData={treeData}
          />
          }
         
        </Form.Item>
      </Form>
    </Spin>
     
</Modal>
}

const RoleNewCom = forwardRef(RoleNew);
export default withRouter(RoleList)
